// server.js

const express = require('express');
const http = require('http');
const socketIO = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketIO(server);

const PORT = 3000;

app.use(express.static('public'));

let users = []; // 存储用户列表，数组形式 [{ username, socket }, ...]

io.on('connection', (socket) => {
    console.log('新用户已连接');

    // 注册用户名
    socket.on('register', (username) => {
        if (!username || typeof username !== 'string') {
            return socket.emit('error', '用户名不能为空');
        }
        if (users.some(u => u.username === username)) {
            return socket.emit('error', '用户名已被占用');
        }

        const newUser = { username, socket, count: 0 };
        users.push(newUser);

        socket.emit('registered', username);

        // 更新所有用户的在线列表，包括 count
        broadcastUserList();

        console.log(`用户 ${username} 已注册`);
    });

    // 发送私聊消息
    socket.on('private message', ({ to, message }) => {
        const fromSocketId = socket.id;
        const fromUser = users.find(u => u.socket.id === fromSocketId);
        if (!fromUser) return;

        const toUser = users.find(u => u.username === to);
        if (toUser) {
            // 如果目标用户离线或不在聊天窗口中，可以增加未读计数
            toUser.count += 1; // 增加未读消息数

            toUser.socket.emit('private message', {
                from: fromUser.username,
                message
            });
        }
    });

    function broadcastUserList() {
        const userList = users.map(u => ({
            username: u.username,
            count: u.count
        }));
        io.emit('user list', userList);
    }

    // 用户断开连接
    socket.on('disconnect', () => {
        const index = users.findIndex(u => u.socket.id === socket.id);
        if (index !== -1) {
            const user = users[index];
            console.log(`用户 ${user.username} 已断开连接`);
            users.splice(index, 1);
        }

        broadcastUserList();
    });

    // 用户退出
    socket.on('logout', () => {
        const index = users.findIndex(u => u.socket.id === socket.id);
        if (index !== -1) {
            const user = users[index];
            console.log(`用户 ${user.username} 已退出`);
            users.splice(index, 1);
        }

        broadcastUserList();
    });
});

server.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
});